package com.itcast.dao.impl;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import com.itcast.dao.StudentDao;
import com.itcast.domain.Student;

public class StudentDaoImpl extends HibernateDaoSupport implements StudentDao{
	
	 private JdbcTemplate jdbcTemplate;  
     
	    public JdbcTemplate getJdbcTemplate() {  
	        return jdbcTemplate;  
	    }  
	     
	    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
	        this.jdbcTemplate = jdbcTemplate;  
	    }  

	@Override
	public void save(Student student) {
		this.getHibernateTemplate().save(student);
	}

	@Override
	public void update(Student student) {
		this.getHibernateTemplate().update(student);
	}

	@Override
	public void delete(Student student) {
		this.getHibernateTemplate().delete(student);
	}

	@Override
	public List<Student> findById(Integer id,int pageIndex) {
		String sql = "select * from student where db_id = ?  order by db_id LIMIT ?,?;";
		RowMapper<Student> rowMapper = BeanPropertyRowMapper.newInstance(Student.class);
		return (List<Student>) this.jdbcTemplate.query(sql, rowMapper,id,(pageIndex - 1) * 50,pageIndex * 50);
	}

	@Override
	public Student findByIdAndFormId(Integer id, String form_id) {
		String sql = "select * from student where db_id = ?  and form_id = ?;";
		RowMapper<Student> rowMapper = BeanPropertyRowMapper.newInstance(Student.class);
		return this.jdbcTemplate.query(sql, rowMapper,id,form_id).get(0);
	}

	@Override
	public void setNull(Integer dbid, String name) {
		String sql = "update  student set "+ name +" = null where db_id = ?;";
		this.jdbcTemplate.update(sql, new Object[] {dbid});  
	}

	@Override
	public void updateForm_id(Integer dbid, String form_id, String value) {
		String sql = "update  student set form_id = ? where db_id = ? and form_id = ?;";
		this.jdbcTemplate.update(sql, new Object[] {value,dbid,form_id});  
	}

}
